package cool.mtc.core.result;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author 明河
 */
@Data
@NoArgsConstructor
@AllArgsConstructor(staticName = "of")
public class Result<T> {
    private static final ObjectMapper MAPPER = new ObjectMapper();

    private int code;
    private String msg;
    private T data;

    /**
     * msg中的可能存在的变量，对msg的补充
     */
    @JsonIgnore
    private Object[] args;

    public static <T> Result<T> ofData(T data) {
        return of(ResultConstant.OK.getCode(), ResultConstant.OK.getMsg(), data);
    }

    public static <T> Result<T> of(int code, String msg) {
        return of(code, msg, null);
    }

    public static <T> Result<T> of(int code, String msg, T data) {
        return of(code, msg, data, null);
    }

    public Result<T> newInstance() {
        return new Result<>(this.getCode(), this.getMsg(), this.getData(), this.getArgs());
    }

    public Result<T> args(Object... args) {
        this.args = args;
        return this;
    }

    public Result<T> msg(String msg) {
        this.msg = msg;
        return this;
    }

    public String toJson() {
        try {
            return MAPPER.writeValueAsString(this);
        } catch (JsonProcessingException ex) {
            return null;
        }
    }
}
